import config from '@/common/config.js'
import store from '@/store/index.js'
import {
	min
} from 'lodash'
import QQMapWX from './qqmap-wx-jssdk.min.js'


const showLoading = function(title) {
	if (!title)
		title = "加载中"
	uni.showLoading({
		title: title,
		mask: true
	});
}



const telPhone = function(phone) {
	console.log("osName", uni.getSystemInfoSync().osName)
	if (uni.getSystemInfoSync().osName == "ios" && phone.indexOf("+86") < 0)
		phone = "+86 " + phone;
	uni.makePhoneCall({
		phoneNumber: '' + phone,
		success: function() {
			console.log("拨打电话成功！")
		},
		fail: function() {
			console.log("拨打电话失败！")
		}

	})
}

const distance = function(lat1, lng1, lat2, lng2) {
	lat1 = Number(lat1)
	lng1 = Number(lng1)
	lat2 = Number(lat2)
	lng2 = Number(lng2)
	// console.log("lat1", lat1)
	// console.log("lng1", lng1)
	// console.log("lat2", lat2)
	// console.log("lng2", lng2)
	// let lat2 = that.myLocation.lat;
	// let lng2 = that.myLocation.lng;
	let rad1 = lat1 * Math.PI / 180.0;
	let rad2 = lat2 * Math.PI / 180.0;
	let a = rad1 - rad2;
	let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) *
		Math.cos(
			rad2) * Math.pow(
			Math.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toString();
	s = s.substring(0, s.indexOf('.') + 4);
	return s
}

const getAddress = function(lng, lat) {
	return new Promise((resove, reject) => {
		const qqmapsdk = new QQMapWX({
			key: 'WASBZ-OEOKW-YKMRQ-RIFQB-QQF5V-45BV5', //之前在腾讯位置服务申请的key
		})
		qqmapsdk.reverseGeocoder({
			location: {
				latitude: lat,
				longitude: lng,
			},
			success: (res) => {
				resove(res)
			},
			fail: (e) => {
				reject(e)
				// uni.showToast({
				//   title: '定位失败',
				//   duration: 2000,
				//   icon: 'none',
				// })
			},
		})
	})
}

const geocoder = function(address) {
	return new Promise((resove, reject) => {
		const qqmapsdk = new QQMapWX({
			key: 'WASBZ-OEOKW-YKMRQ-RIFQB-QQF5V-45BV5', //之前在腾讯位置服务申请的key
		})
		qqmapsdk.geocoder({
			address: address,
			region: "温州市",
			success: (res) => {
				resove(res)
			},
			fail: (e) => {
				reject(e)
			},
		})
	})
}

const getLocation = function() {
	let that = this
	uni.getLocation({
		type: 'gcj02',
		success: function(res) {
			let longitude = res.longitude
			let latitude = res.latitude
			let params = {
				city: "未获取到",
				name: "未获取到",
				lng: longitude,
				lat: latitude,
			}
			uni.setStorageSync('setLocation', params);
			getAddress(longitude, latitude)
				.then((res) => {
					let params = {
						city: res.result.address_component.city,
						name: res.result.address_reference.landmark_l2.title,
						lng: longitude,
						lat: latitude,
					}
					console.log('解析成功', params)
					uni.setStorageSync('setLocation', params);
				})
				.catch((e) => {
					// uni.showModal({
					// 	content: "解释地址失败" + JSON.stringify(e)
					// })
					console.log(e, '解释地址失败')
				})
		},
		fail(err) {
			console.log(err, '获取经纬度失败')
			// uni.showModal({
			// 	title: "温馨提示",
			// 	content: "请先打开位置获取",
			// 	showCancel: false,
			// 	success: function() {
			// 		getLocation()
			// 	}
			// })
		},
	});
}

const openMap = function(lat, lng) {
	uni.chooseLocation({
		latitude: lat,
		longitude: lng
	});
}

const gePpreviewImage = function(urls) {
	let urlarr = urls.split("|");
	let arr = []
	urlarr.forEach(item => {
		arr.push(imgageUrl(item))
	})
	uni.previewImage({
		urls: arr
	})
}
const navto = function(url, data) {
	// url参数拼接
	url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

	uni.navigateTo({
		url,
		success: (e) => {
			console.log("success", e)
		},
		fail: (e) => {
			console.log("fail", e)
		}
	})
}

const gotoMiniProgram = function(appid, url) {
	if (!appid)
		return false;
	uni.navigateToMiniProgram({
		appId: appid,
		path: url,
		success(res) {
			// 打开成功
			console.log("打开成功")
		}
	})
}

const redirectTo = function(url, data) {
	// url参数拼接
	url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

	uni.redirectTo({
		url,
		success: (e) => {
			console.log("success", e)
		},
		fail: (e) => {
			console.log("fail", e)
		}
	})
}

const reLaunch = function(url, data) {
	// url参数拼接
	url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

	uni.reLaunch({
		url,
		success: (e) => {
			console.log("success", e)
		},
		fail: (e) => {
			console.log("fail", e)
		}
	})
}

const switchTabTo = function(url) {

	uni.switchTab({
		url,
		success: (e) => {
			console.log("success", e)
		},
		fail: (e) => {
			console.log("fail", e)
		}
	})
}

// 返回上一页
const navBack = function() {
	uni.navigateBack();
}

const reload = function() {
	// 页面重载
	const pages = getCurrentPages()
	// 声明一个pages使用getCurrentPages方法
	const curPage = pages[pages.length - 1]
	// 声明一个当前页面
	curPage.onLoad(curPage.options) // 传入参数
	curPage.onShow()
	curPage.onReady()
	// 执行刷新
}

const imgageUrl = function(url) {
	if (url) {
		if (url.indexOf("profile") >= 0) {
			return config.baseUrl + url
		} else {
			return url
		}
	} else {
		return "/static/errorImage.jpg"
	}

}



const isLogin = function() {
	return store.state.hasLogin;
}

const htmlPost = function(url, data, token, method) {
	// console.log("store.state.token", store.state.token)
	return new Promise(async resolve => {
		let statetoken = store.state.userInfo.token;
		if (token)
			statetoken = token
		let me = 'POST'
		if (method)
			me = method
		uni.request({
			url: config.baseUrl + url,
			data: data,
			header: {
				"Content-Type": "application/x-www-form-urlencoded",
				"Authorization": statetoken
			},
			method: me,
			success(e) {
				// console.log("e", e)
				if (e.data.code == 500 && e.data.msg == "授权信息超时、错误！") {
					uni.navigateTo({
						url: '/pages/login/login'
					})
					return false
				}
				resolve(e)
			}
		})
	})
}



const htmlPostMachinePay = function(url, data, method) {
	return new Promise(async resolve => {
		uni.request({
			url: "https://weilai.wlsj.site" + url,
			data: data,
			header: {
				"Content-Type": "application/json",
				"ClientCode": "huashouQoMYyIhtPYBnpRL8dllV"
				// "Authorization": "Bearer " + token
			},
			method: !method ? 'POST' : method,
			success(e) {
				resolve(e)
			}
		})
	})
}

const isLoginUrl = function() {
	console.log("store.state.userInfo.nickName", store.state.userInfo.nickName)
	if (!store.state.userInfo.nickName && store.state.userInfo.nickName == "") {
		uni.showModal({
			title: '温馨提示',
			content: '请先填写用户基本信息',
			success(res) {
				if (res.confirm) {
					uni.setStorageSync('showUser', true);
					uni.reLaunch({
						url: '/pages/center/index'
					})
				} else {
					let pages = getCurrentPages();
					if (pages.length > 1)
						uni.navigateBack()
					else {
						uni.switchTab({
							url: `/pages/index/index`
						})
					}
					// uni.navigateBack();
				}
			}
		})
		return false
	}
	return true
}

const formatRichText = function(html) {
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
			'max-width:100%;');
		return match;
	});
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
	return newContent;
}


// 格式化参数对象
function param(data) {
	let url = ''
	for (var k in data) {
		let value = data[k] !== undefined ? data[k] : ''
		url += '&' + k + '=' + encodeURIComponent(value)
	}
	return url ? url.substring(1) : ''
}


const jfLevel = function(num) {
	if (num >= 1500)
		return 5
	else if (num >= 800)
		return 4
	else if (num >= 500)
		return 3
	else if (num >= 200)
		return 2
	else
		return 1
}

const jfLevelName = function(num) {
	let arr = ["青铜", "铂金", "黄金", "钻石", "王者"]
	return arr[num - 1]
}


export {
	navto,
	redirectTo,
	switchTabTo,
	reLaunch,
	navBack,
	imgageUrl,
	isLoginUrl,
	isLogin,
	htmlPost,
	reload,
	formatRichText,
	getAddress,
	gePpreviewImage,
	getLocation,
	distance,
	telPhone,
	showLoading,
	htmlPostMachinePay,
	gotoMiniProgram,
	openMap,
	jfLevel,
	jfLevelName,
	geocoder
}